package com.hospital.insurancedip.module.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.hospital.common.core.exception.ExceptionPrint;
import com.hospital.common.core.module.entity.NFC.NFCResponse;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.DataBaseValue;
import com.hospital.common.core.utils.DateUtil;
import com.hospital.common.core.utils.StringUtil;
import com.hospital.insurancedip.async.WxPayFunc;
import com.hospital.insurancedip.handler.InvocationFactory;
import com.hospital.insurancedip.handler.MessageInfo;
import com.hospital.insurancedip.module.controller.vo.BatchUpDip;
import com.hospital.insurancedip.module.entity.InsuranceLogs;
import com.hospital.insurancedip.module.mapper.InsuranceLogsMapper;
import com.hospital.insurancedip.module.service.InsuranceLogsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * prepayin
 *
 * @description 接口转调
 * @author:louislau
 * @create 2019-11-08 08:56:25
 **/

@RestController
@RequestMapping("/dip")
@Slf4j
public class InfoTransfer {

    @Autowired
    private WxPayFunc wxPayFunc;

    @Resource
    private InsuranceLogsMapper insuranceLogsMapper;

    @Resource
    private InsuranceLogsService insuranceLogsService;


    @RequestMapping("/sendPeople")
    public Tip wxPayTransfer(@RequestBody String params, HttpServletResponse httpServletResponse) throws InterruptedException {
        JSONObject jsonObject = JSON.parseObject(params);
        JSONArray data = jsonObject.getJSONArray("data");
        String tableName = jsonObject.getString("tableName");
        String action = jsonObject.getString("action");
        String endesUrl = insuranceLogsMapper.getEncryptionUrl();
        if (!action.equals("DELETE")) {
            for (Object jsonObject1 : data) {
                String uploadDate = JSON.parseObject(jsonObject1.toString()).getString("UPLOAD_DATE");
                String serialNo = JSON.parseObject(jsonObject1.toString()).getString("SERIAL_NO");
                //通过配置地址查看是否转发
                String url = insuranceLogsMapper.selectUrl(serialNo
                        + "_URL");
                if (!Objects.isNull(url)) {
                    //因表中无主键，因此根据查询条件查出几条就推送
                    QueryWrapper<InsuranceLogs> queryWrapper = new QueryWrapper<>();
                    queryWrapper.apply(" SERIAL_NO = {0} " +
                            "and UPLOAD_DATE =to_date({1},'yyyy-mm-dd hh24:mi:ss')", serialNo, uploadDate);
                    List<InsuranceLogs> insuranceLogsList = insuranceLogsMapper.
                            selectList(queryWrapper);
                    if (!Objects.isNull(insuranceLogsList)) {
                        for (InsuranceLogs insuranceLogs : insuranceLogsList) {
                            NFCResponse nfcResponse = new NFCResponse();
                            nfcResponse.setEncData("");
                            nfcResponse.setAppId("1G00VOLSP0143F60C80A00005F9F40EF");
                            String insuranceJson = insuranceLogs.getInsuranceJson();
                            Object parse = JSON.parse(insuranceJson);
                            JSONObject jsonObjectInput = JSON.parseObject(parse.toString());
                            nfcResponse.setData(jsonObjectInput.get("input"));
//                            nfcResponse.setUrl(endesUrl);
                            nfcResponse.setSignType("SM3");
                            String printLog = "\r\n传输数据:" + data + "\r\ntableName:" + tableName +
                                    "\r\naction:" + action +
                                    "\r\ninfo:" + insuranceLogs.getSerialNo() +
                                    "\r\nupload_date:" + DateUtil.format(insuranceLogs.getUploadDate(), "yyyy-MM-dd HH:mm:ss") +
                                    "\r\npatient_id:" + insuranceLogs.getPatientId()
                                    + "\r\nvisit_id:" + insuranceLogs.getVisitId();
                            printLog = printLog + "\r\n人保加密接口入参：" + JSON.toJSONString(nfcResponse);
                            Map<String, String> mapEnc = wxPayFunc.enc(nfcResponse, endesUrl);
                            if (mapEnc.containsKey("enc")) {
                                String enc = mapEnc.get("enc");
                                printLog = printLog + "\r\n人保加密接口出参、人保推送入参：" + enc + "\r\n" + mapEnc.get("responseDescription");
                                if (enc != null) {
                                    wxPayFunc.wxPay(enc, url, printLog);
                                }
                            } else {
                                printLog = printLog + "\r\n" + mapEnc.get("responseDescription");
                                log.info(printLog);
                            }
                        }
                    }
                }

            }
        }
        return new SuccessTip("已执行");
    }

    @RequestMapping("/api")
    public Tip dipApi(@RequestBody String params, HttpServletResponse httpServletResponse) throws InterruptedException {
        Tip tip = null;
        String startTime = DateUtil.getAllTime();
        StopWatch stopwatch2 = new StopWatch();
        stopwatch2.start();
        String infno = "";
        try {
            JSONObject jsonObject = JSON.parseObject(params);
            infno = jsonObject.getString("infno");
            MessageInfo tableImp = InvocationFactory.getTableImp("N", infno);
            tip = new SuccessTip(null);
            tip.setData(jsonObject);
            tip = tableImp.getHisInfo(tip);
        } catch (Exception e) {
            tip = new ErrorTip(203, e.getMessage());
            stopwatch2.stop();
            String endTime = DateUtil.getAllTime();
            long end = SystemClock.now();
            ExceptionPrint.printCommErrorString("银海DIP统一接口-事件：" + infno,
                    params,
                    String.valueOf(tip.getCode())
                    , tip.getMessage() + "--返回内容：" + tip.getData(), startTime, endTime, String.valueOf(stopwatch2.getTotalTimeSeconds()));
        }
        return tip;
    }

    /**
     * @param params:
     * @description:批量上传结算并归档的（410100、230401、230501）及结算未归档的（230401、230501）
     * @author: lvyao
     * @date: 2023/7/12 9:07
     * @return: com.hospital.insurancedip.result.Tip
     **/
    @RequestMapping("/batchAllApi")
    public Tip dipApi(@RequestBody String params) throws InterruptedException {
        Tip tip = null;
        String startTime = DateUtil.getAllTime();
        StopWatch stopwatch2 = new StopWatch();
        stopwatch2.start();
        JSONObject jsonObject = JSON.parseObject(params);
        String beginDate = jsonObject.getString("begin_date");
        String endDate = jsonObject.getString("end_date");
        String type = jsonObject.getString("type");
        String hospitalCode = jsonObject.getString("hospital_code");
        List<BatchUpDip> batchUpDipList = new ArrayList<>();
        if (type.equals("1")) {
            batchUpDipList.addAll(insuranceLogsService.getBatchUpDip(beginDate, endDate, DataBaseValue.getDataBaseTopic(hospitalCode)));
            batchUpDipList.addAll(insuranceLogsService.getUnUpDip(beginDate, endDate, DataBaseValue.getDataBaseTopic(hospitalCode)));
        } else {
            batchUpDipList.addAll(insuranceLogsService.getSettleDataAllDip(beginDate,endDate, DataBaseValue.getDataBaseTopic(hospitalCode)));
        }
        if (ObjectUtil.isNotNull(batchUpDipList)) {
            for (
                    BatchUpDip batchUpDip : batchUpDipList) {
                List<InsuranceLogs> insuranceLogsList = insuranceLogsService.selectbyPid(batchUpDip.getPatientId(),batchUpDip.getVisitId(), DataBaseValue.getDataBaseTopic(hospitalCode));
                if (ObjectUtil.isNotNull(insuranceLogsList)) {
                    for (InsuranceLogs insuranceLogs : insuranceLogsList) {
                        String infno = insuranceLogs.getSerialNo();
                        try {
                            String insuranceJson = insuranceLogs.getInsuranceJson();
                            boolean isSend = true;
                            //银海DIP数据传输
                            if (infno.equals("2304")||infno.equals("2304_B")) {
                                insuranceJson = StringUtil.asciiToString(new String(insuranceLogs.getInsuranceJsonOut()));
                                Object parse = JSON.parse(insuranceJson);
                                JSONObject jsonObjectInput = JSON.parseObject(parse.toString());
                                JSONObject output = jsonObjectInput.getJSONObject("output");
                                JSONObject setlinfo = output.getJSONObject("setlinfo");
                                String mdtrt_id = setlinfo.getString("mdtrt_id");
                                String setl_id = setlinfo.getString("setl_id");
                                String settleFrundFlag = insuranceLogsService.getSettleFrundFlag(setl_id, mdtrt_id, DataBaseValue.getDataBaseTopic(hospitalCode));
                                if (StringUtils.isNotEmpty(settleFrundFlag) && settleFrundFlag.equals("1")) {
                                    isSend = false;
                                }
                                String logsInsuranceJson = insuranceLogs.getInsuranceJson();
                                Object inputStr = JSON.parse(logsInsuranceJson);
                                JSONObject jsonObjectInputStr = JSON.parseObject(inputStr.toString());
                                jsonObjectInputStr.put("input", output);
                                insuranceJson = jsonObjectInputStr.toJSONString();
                            }
                            if (isSend) {
                                Object parse = JSON.parse(insuranceJson);
                                JSONObject jsonObjectInput = JSON.parseObject(parse.toString());
                                tip = new SuccessTip(null);
                                tip.setData(jsonObjectInput);
                                MessageInfo tableImp = InvocationFactory.getTableImp("N", infno);
                                tip = tableImp.getHisInfo(tip);
                            }
                        } catch (Exception e) {
                            tip = new ErrorTip(203, e.getMessage());
                            stopwatch2.stop();
                            String endTime = DateUtil.getAllTime();
                            long end = SystemClock.now();
                            ExceptionPrint.printCommErrorString("银海DIP统一接口-批量事件：" + infno,
                                    params,
                                   String.valueOf( tip.getCode())
                                    , tip.getMessage() + "--返回内容：" + tip.getData(), startTime, endTime, String.valueOf(stopwatch2.getTotalTimeSeconds()));
                        }
                    }
                }
            }
        }
        return tip;
    }

}
